import java.util.Random;
import java.util.concurrent.*;

/**
 * Created by Administrator on 2016/4/5.
 */
public class E30_PipedIO {

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Character> queue = new LinkedBlockingQueue<Character>();
        Sender sender = new Sender(queue);
        Receiver receiver = new Receiver(queue);
        ExecutorService exec = Executors.newCachedThreadPool();
        exec.execute(sender);
        exec.execute(receiver);
        TimeUnit.SECONDS.sleep(4);
        exec.shutdownNow();
    }

}

class Sender implements Runnable {
    private Random rand = new Random(47);
    private BlockingQueue<Character> queue;

    public Sender(BlockingQueue<Character> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            for (char c = 'A'; c < 'z'; c++) {
                queue.put(c);
                TimeUnit.MILLISECONDS.sleep(rand.nextInt(500));
            }
        } catch (InterruptedException e) {
            System.out.println(e + " Sender sleep interrupted");
        }
    }
}

class Receiver implements Runnable {
    private BlockingQueue<Character> queue;

    public Receiver(BlockingQueue<Character> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            while (true) {
                System.out.println("Read: " + (char)queue.take() + ", ");
            }
        } catch (InterruptedException e) {
            System.out.println(e + " Receiver read exception");
        }
    }
}